//
//  XMCodeInputView.m
//  POP_User
//
//  Created by Rowling on 2019/4/3.
//  Copyright © 2019年 Rowling. All rights reserved.
//

#import "XMCodeInputView.h"
#import "InputCell.h"
#import "UIView+SGExtension.h"
@interface XMCodeInputView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@property(nonatomic,assign)BOOL  canSendComplete;

@end

@implementation XMCodeInputView

-(ForbidInputTextField *)textField {
    if (_textField == nil) {
        _textField = [[ForbidInputTextField alloc]init];
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        _textField.delegate = self;
    }
    return _textField;
}

-(NSString *)text {
    return self.textField.text;
}

-(void)clear {
    self.textField.text = @"";
    [self textFieldDidChange:self.textField];
}

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self setUI];
    }
    return self;
}


-(void)awakeFromNib {
    [super awakeFromNib];
    self.canSendComplete = YES;
//    [self setUI];
}



-(BOOL)becomeFirstResponder {
   return [self.textField becomeFirstResponder];
}

-(CGSize)itemSize {
    CGFloat width = (self.sgSize.width - self.layoutInset.left - self.layoutInset.right - (self.space * (self.inputCount - 1)) - 1) / self.inputCount;
    NSLog(@"%f",width);
    NSLog(@"%f",self.layoutInset.left);
    NSLog(@"%f",self.layoutInset.right);
    
    return CGSizeMake(width, self.sgSize.height);
}

-(void)setUI {
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.itemSize = CGSizeMake(SG_SCREEN_WIDTH / 4, 100);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 10, 10) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.scrollEnabled = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self addSubview:self.textField];
    [self addSubview:self.collectionView];
//    self.layoutInset = UIEdgeInsetsMake(0, 0, 0, 0);
//    self.ItemSize = CGSizeMake(SG_SCREEN_WIDTH / 5, SG_SCREEN_WIDTH / 5);
    
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"InputCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    

    [self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}





-(void)textFieldDidChange:(UITextField *)textFiled {
    
    NSArray * cells = [self.collectionView visibleCells];
    if(self.textField.text.length > 0 && self.textField.text.length >= cells.count) {
        self.textField.text = [self.textField.text substringToIndex:cells.count];
    }
    for (int i = 0; i < cells.count ; i ++) {
        InputCell * cell = cells[i];
        if (i < self.textField.text.length) {
            cell.contentLabel.text = [NSString stringWithFormat:@"%c",[self.textField.text characterAtIndex:i]];
            cell.psdView.hidden = !self.cellConfig.securityInput;
        } else {
            cell.psdView.hidden = YES;
            cell.contentLabel.text = @"";
        }
    }

    
    if (self.textField.text.length == self.inputCount && self.delegate != nil && [self.delegate respondsToSelector:@selector(inputComplete:)]) {
        if (self.canSendComplete == YES) {
            self.canSendComplete = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.canSendComplete = YES;
            });
            [self.delegate inputComplete:self.textField.text];
            NSLog(@"最终结果%@",textFiled.text);
        } 
    }
}

-(void)layoutSubviews {
    [super layoutSubviews];
    self.textField.frame = CGRectMake(self.layoutInset.left, self.layoutInset.top, self.frame.size.width - self.layoutInset.left - self.layoutInset.right, self.frame.size.height - self.layoutInset.top - self.layoutInset.bottom);
    self.collectionView.frame = self.bounds;//CGRectMake(self.layoutInset.left, self.layoutInset.top, self.frame.size.width - self.layoutInset.left - self.layoutInset.right, self.frame.size.height - self.layoutInset.top - self.layoutInset.bottom);
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.inputCount;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    InputCell * cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
//    cell.backgroundColor = color_gray;
    if (self.cellConfig) {
        cell.backgroundColor = self.cellConfig.backGourndColor;
        cell.contentLabel.font = self.cellConfig.font;
        cell.subLine.hidden = self.cellConfig.hideLine;
        cell.layer.borderWidth = self.cellConfig.borderWidth;
        cell.layer.borderColor = self.cellConfig.borderColor ? self.cellConfig.borderColor.CGColor : [UIColor clearColor].CGColor;
        cell.contentLabel.hidden = self.cellConfig.securityInput;
        cell.layer.cornerRadius = self.cellConfig.cornerRadius;
    }
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self itemSize];
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return self.layoutInset;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.space;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.textField becomeFirstResponder];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * regex = @"^[0-9]*$";
    NSPredicate * pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    BOOL ok = [pre evaluateWithObject:string];
    return ok;
}

-(void)reaload {
    [self layoutIfNeeded];
    [self.collectionView reloadData];
}
@end

@implementation XMCodeInputCellConfig

-(instancetype)init{
    if (self = [super init]) {
        self.backGourndColor = [UIColor whiteColor];
        self.hideLine = NO;
        self.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
    }
    return self;
}

@end
